import React from 'react';
import { withRouter, Link } from 'react-router';
import { connect } from 'react-redux';
import Pagination from 'rc-pagination';
// import Input from '../base/Input.js';
import childrenDevice from '../../actions/childrenDeviceAction.js';
import DeviceRow from '../mui/deviceRow.js';
import Widget from '../mui/Widget.js';
import SearchInput from '../mui/searchInput.js';
import UploadFileInput from '../testPackage/uploadFileInput.js';
import ArrayTool from '../../utils/ArrayUtils.js';


const ChildrenDevice = withRouter(
  React.createClass({
    getInitialState() {
      return {
        pageList: '',
        originalList: [],
        errorMessage: false,
        nullMessage: false,
        cancelDelButton: false,
        uploadValue: '',
        saveData: {},
        pageNumber: 0,
        totalPageNumber: 1,
        oneCategoryName: ''
      };
    },
    componentDidMount() {
      const { fetchChildrenDeviceList, getOneCategory, params } = this.props;
      getOneCategory({ id: params.id });
      fetchChildrenDeviceList({ id: params.id });
      this.delArray = [];
    },
    componentWillReceiveProps(nextProps) {
      const rows = [];
      const errorList = [];
      const nullList = [];
      nextProps.dataList.forEach((item, index) => {
        rows.push(item);
        if (item.error) {
          errorList.push(item);
        }
        if (!item.sn) {  // 为空的元素数组
          nullList.push(item);
        }
      });
      const b = ArrayTool.oneToTwo(rows);
      if (nullList.length) {
        this.setState({ nullMessage: true });
      } else {
        this.setState({ nullMessage: false });
      }
      if (errorList.length > 0) {
        this.setState({ errorMessage: true });
      } else {
        this.setState({ errorMessage: false });
      }
      this.setState(
        {
          originalList: rows,
          pageList: b.data,
          totalPageNumber: (b.totalPageNo) * 10,
          oneCategoryName: nextProps.oneCategoryData.name
        });
    },
    // 添加单条
    // =======
    addOne() {
      const { originalList } = this.state;
      const { addOne } = this.props;
      this.setState({ pageNumber: 0 });
      if (originalList.length !== 0 && !originalList[0].sn) {
        return;
      }
      addOne();
    },
    // 批量添加
    // ======
    batchAdd(e) {
      const { uploadFile } = this.props;
      const data = { filename: 'file', file: e.target.files[0] };
      uploadFile(data);
      this.setState({ uploadValue: '' });
    },
    // 更新单条
    // ======
    updateOne(data) {
      const { originalList } = this.state;
      const { editDevice } = this.props;
      const newPageList = [];
      this.errorList = [];
      // 找出修改对象的数组索引
      // ===================
      const updateObjIndex = originalList.findIndex((obj) =>
        obj.id === data.id
      );
      data.Data.error = false;
      originalList.forEach((item, index) => {
        newPageList.push(item.asMutable());
      });
      // 遍历主数组，判断新修改的值是否重复
      // ============================
      originalList.forEach((item, index) => {
        if ((item.sn === data.Data.sn) && (item.id !== data.id)) {
          data.Data.error = true;
          // updataList.push(item);
        }
      });
      // console.log(updataList);
      // 将修改的值更新到数组
      // ==================
      newPageList[updateObjIndex] = data.Data;
      newPageList.forEach((item, index) => {
        if (item.error) {
          this.errorList.push(item);
        }
      });
      // 遍历错误数组，判断是否该元素是否唯一的
      // =================================
      this.errorList.forEach((itemObj, pindex) => {
        let flog = { error: false };
        newPageList.forEach((item, index) => {
          if (this.errorList[pindex].sn === item.sn && this.errorList[pindex].id !== item.id) {
            flog = { error: true, no: index };
          }
        });
        if (!flog.error) {
          const ObjIndex = newPageList.findIndex((obj) =>
             obj.id === this.errorList[pindex].id
          );
          newPageList[ObjIndex].error = false;
        }
      });
      // }
      editDevice(newPageList);
    },

    delOne(item) {
      const { originalList } = this.state;
      const { editDevice } = this.props;
      const newPageList = [];
      const delItem = [];
      const errorList = [];
      originalList.forEach((obj, index) => {
        newPageList.push(obj.asMutable());
      });
      const delObjIndex = originalList.findIndex((obj) =>
        obj.id === item.id
      );
      const delObj = newPageList.splice(delObjIndex, 1);
      newPageList.forEach((obj, index) => {
        if (obj.sn === item.sn) {
          delItem.push(obj);
        }
      });
      // 删除后，如果剩余和删除元素相同名字的长度为1时，则不存在重复，去掉红色
      // =====================================================================
      if (delItem.length === 1) {
        const remainObjIndex = newPageList.findIndex((obj) =>
          delItem[0].id === obj.id
        );
        newPageList[remainObjIndex].error = false;
      }
      // 查询数组里面error为true的item存在数组
      // =====================================
      newPageList.forEach((itemObj, index) => {
        if (itemObj.error) {
          errorList.push(itemObj);
        }
      });
      // 判断显示重复提示信息是否显示
      // ============================
      if (errorList.length > 0) {
        this.setState({ errorMessage: true });
      } else {
        this.setState({ errorMessage: false });
      }
      this.delArray.push(delObj[0]);
      this.setState({ cancelDelButton: true });
      editDevice(newPageList);
    },
    cancelDelObj() {
      const dataObj = this.delArray.pop();
      const { originalList } = this.state;
      const { editDevice } = this.props;
      const newPageList = [];
      const errorList = [];
      if (!this.delArray.length) {
        this.setState({ cancelDelButton: false });
      }
      originalList.forEach((item, index) => {
        newPageList.push(item.asMutable());
      });

      // 遍历主数组，判断新修改的值是否重复
      // ============================
      dataObj.error = false;
      originalList.forEach((item, index) => {
        if ((item.sn === dataObj.sn) && (item.id !== dataObj.id)) {
          dataObj.error = true;
        }
      });
      // 将修改的值更新到数组
      // =====================
      newPageList.unshift(dataObj);
      // 查询数组里面error为true的item存在数组
      // =====================================
      newPageList.forEach((itemObj, index) => {
        if (itemObj.error) {
          errorList.push(itemObj);
        }
      });
      // 判断显示重复提示信息是否显示
      // ============================
      if (errorList.length > 0) {
        this.setState({ errorMessage: true });
      } else {
        this.setState({ errorMessage: false });
      }
      editDevice(newPageList);
    },
    submitData() {
      console.log(this.delArray);
      const { pageList } = this.state;
      const { saveChildrenDevice, params } = this.props;
      const formData = ArrayTool.twoToOne(pageList);
      saveChildrenDevice({ data: formData, id: params.id }, this.props.router);
    },
    pagination(pageNo) {
      this.setState({ pageNumber: pageNo - 1 });
    },
    search(targetData) {
      const { originalList } = this.state;
      const searchPagelist = [];
      originalList.forEach((item) => {
        if (item.sn.indexOf(targetData.value) === -1) {
          return;
        }
        searchPagelist.push(item);
      });
      const searchdataObj = ArrayTool.oneToTwo(searchPagelist);
      this.setState({ pageList: searchdataObj.data, totalPageNumber: (searchdataObj.totalPageNo) * 10, pageNumber: 0 });
    },
    render() {
      const { pageNumber, pageList, totalPageNumber, errorMessage, cancelDelButton, oneCategoryName, nullMessage } = this.state;
      // const { oneCategoryData } = this.props;
      const deviceList = pageList[pageNumber] ? pageList[pageNumber] : [];
      const button = <button className="btn btn-primary w60 mr12" onClick={this.submitData}>保存</button>;
      const disableButton = <button className="btn btn-disable w60 mr12" disabled="disabled">保存</button>;
      return (
        <div>
          <Widget widgetHeader={'测试类列表'} widgetHeaderTwo={'子设备管理'} />
          <div className="widget-body">
            <div className="mw400">
              <span className="title-two" title={oneCategoryName}><p>{oneCategoryName}</p></span>
              {errorMessage || nullMessage ? disableButton : button}
              <button className="btn btn-cancel w60 mr12">
                <Link to="/testCategory" activeClassName="active">取消</Link>
              </button>
              {cancelDelButton ? <button onClick={this.cancelDelObj} className="btn btn-red w100 mr12">撤销删除</button> : ''}
              {errorMessage ? <span className="text-danger">SN号重复，请重新输入。</span> : ''}
              <div className="pull-right">
                <button onClick={this.addOne} className="btn btn-green w100 mr12">单项添加</button>
                <UploadFileInput
                  onChange={this.batchAdd}
                  className={"btn btn-primary w100 relative mr12"}
                  InputClass={'w100'}
                  id={'upload_file'}
                  buttonMsg={'批量添加'}
                  accept={".txt"}
                  value={this.state.uploadValue}
                />
                <SearchInput placeholder={"SN号"} onSearch={this.search} className="pull-right" />
              </div>
              <div className="clearfix" />
            </div>
            <table className="table table-hover tr40 td0">
              <thead>
                <tr>
                  <th className="m-w490">SN号</th>
                  <th className="m-w490">备注</th>
                  <th className="m-w90">操作</th>
                </tr>
              </thead>
              <tbody>
              {
                deviceList.map((item, index) =>
                  <DeviceRow
                    key={index + "" + Math.ceil(Math.random() * 1000)}
                    item={item}
                    pageNo={pageNumber}
                    index={index}
                    updateOne={this.updateOne}
                    delOne={this.delOne}
                  />
                )
              }
              </tbody>
            </table>
            <div className="mt50 mb100">
              <Pagination className="ant-pagination" defaultCurrent={1} current={pageNumber + 1} total={totalPageNumber} onChange={this.pagination} />
            </div>
          </div>
        </div>
      );
    }
  })
);

const mapStateToProps = function (state) {
  return {
    childrenDeviceList: state.childrenDevice.childrenDeviceList,
    dataList: state.childrenDevice.data_list,
    oneCategoryData: state.testCategory.oneCategoryData
    // batchDataList: state.childrenDevice.batchDataList
    // saveErrorMsg: state.childrenDevice.testPackageMsg,
    // uploadErrorMsg: state.childrenDevice.uploadMsg,
  };
};

module.exports = connect(mapStateToProps, childrenDevice)(ChildrenDevice);
